package de.thetaphi.forbiddenapis;

/*
 * (C) Copyright 2013 Uwe Schindler (Generics Policeman) and others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DeprecatedGen implements Opcodes {
  
  final static String NL = System.getProperty("line.separator", "\n");
  final SortedSet<String> deprecated = new TreeSet<String>();
  final String javaVersion, header;
  
  DeprecatedGen(String javaVersion) {
    this.javaVersion = javaVersion;
    if (!System.getProperty("java.version").startsWith(javaVersion))
      throw new IllegalArgumentException("Java version mismatch: build " + System.getProperty("java.version") + " != expected " + javaVersion);
    this.header = new StringBuilder()
      .append("# This file contains API signatures extracted from the rt.jar file").append(NL)
      .append("# shipped with the class library of Oracle's Java Runtime Environment.").append(NL)
      .append("# It is provided here for reference, but can easily regenerated by executing:").append(NL)
      .append("# $ java ").append(DeprecatedGen.class.getName()).append(' ').append(javaVersion).append(" /path/to/rt.jar /path/to/this/file.txt").append(NL)
      .append(NL)
      .append("# This file contains all public, deprecated API signatures in Java version ").append(javaVersion)
        .append(" (extracted from build ").append(System.getProperty("java.version")).append(").").append(NL)
      .append(NL)
      .append("@defaultMessage Deprecated in Java ").append(javaVersion).append(NL)
      .append(NL)
      .toString();
  }
  
  protected boolean isDeprecated(int access) {
   return ((access & (ACC_PUBLIC | ACC_PROTECTED)) != 0 && (access & ACC_DEPRECATED) != 0);
  }
  
  protected boolean isInternalClass(String className) {
    return className.startsWith("sun.") || className.startsWith("com.sun.") || className.startsWith("com.oracle.") || className.startsWith("jdk.")  || className.startsWith("sunw.");
  }

  void checkClass(final ClassReader reader) {
    final String className =  Type.getObjectType(reader.getClassName()).getClassName();
    // exclude internal classes like Unsafe,... and non-public classes!
    // Note: reader.getAccess() does no indicate if class is deprecated, as this is a special
    // attribute or annotation (both is handled later), we have to parse the class - this is just early exit!
    if ((reader.getAccess() & ACC_PUBLIC) == 0 || isInternalClass(className)) {
      return;
    }
    reader.accept(new ClassVisitor(ASM5) {
      boolean classDeprecated = false;
    
      @Override
      public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        if (isDeprecated(access)) {
          deprecated.add(className);
          classDeprecated = true;
        }
      }

      @Override
      public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
        if (!classDeprecated && isDeprecated(access)) {
          final Type[] args = Type.getType(desc).getArgumentTypes();
          final StringBuilder sb = new StringBuilder(className).append('#').append(name).append('(');
          boolean comma = false;
          for (final Type t : args) {
            if (comma) sb.append(',');
            sb.append(t.getClassName());
            comma = true;
          }
          sb.append(')');
          deprecated.add(sb.toString());
        }
        return null;
      }
        
      @Override
      public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) {
        if (!classDeprecated && isDeprecated(access)) {
          deprecated.add(className + '#' + name);
        }
        return null;
      }
    }, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
  }
  
  void parseRT(InputStream in) throws IOException  {
    final ZipInputStream zip = new ZipInputStream(in);
    ZipEntry entry;
    while ((entry = zip.getNextEntry()) != null) {
      try {
        if (entry.isDirectory()) continue;
        if (entry.getName().endsWith(".class")) {
          final ClassReader classReader;
          try {
            classReader = new ClassReader(zip);
          } catch (IllegalArgumentException iae) {
            // unfortunately the ASM IAE has no message, so add good info!
            throw new IllegalArgumentException("The class file format of your rt.jar seems to be too recent to be parsed by ASM (may need to be upgraded).");
          }
          checkClass(classReader);
        }
      } finally {
        zip.closeEntry();
      }
    }
  }
  
  void writeOutput(OutputStream out) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
    writer.write(header);
    for (final String s : deprecated) {
      writer.write(s);
      writer.newLine();
    }
    writer.flush();
    System.err.println("Deprecated API signatures for Java version " + javaVersion + " written successfully.");
  }

  public static void main(String... args) throws Exception {
    if (args.length != 3) {
      System.err.println("Invalid parameters; must be: java_version /path/to/rt.jar /path/to/outputfile.txt");
      System.exit(1);
    }
    System.err.println("Reading '" + args[1] + "' and extracting deprecated APIs to signature file '" + args[2]+ "'...");
    final InputStream in = new FileInputStream(args[1]);
    try { 
      final DeprecatedGen parser = new DeprecatedGen(args[0]);
      parser.parseRT(in);
      final FileOutputStream out = new FileOutputStream(args[2]);
      try {
        parser.writeOutput(out);
      } finally {
        out.close();
      }
    } finally {
      in.close();
    }
  }
}
